#include "m_max7219.h"
#include "m_spi.h"
#include "m_time.h"
#include "m_log.h"

static int m_max2719_reg_write(unsigned char reg, unsigned char val);

int m_max2719_init()
{
    int r = m_gpio_init();
    if (r != 0) {
        return r;
    }
    r = m_spi_init();
    if (r != 0) {
        return r;
    }
    m_sleep(1000); /* 1000 */
    m_max2719_reg_write(MAX7219_SHUT_DOWN, 0x01);
    m_max2719_reg_write(MAX7219_DISPLAY_TEST, 0x00);
    m_max2719_reg_write(MAX7219_DECODE_MODE, 0xff);
    m_max2719_reg_write(MAX7219_SCAN_LIMIT, 0x07);
    m_max2719_reg_write(MAX7219_INTENSITY, 0x04);
    m_sleep(1000);
    return 0;
}
int m_max2719_show(unsigned char idx, unsigned char val)
{
    m_max2719_reg_write(idx, val);
}


static int m_max2719_reg_write(unsigned char reg, unsigned char val)
{
    unsigned int size_ = 2;
    unsigned char buf_[size_];
    buf_[0] = reg;
    buf_[1] = val;
    #ifdef M_LOG_DEBUG
    unsigned char hex[size_ * 2 + 1];
    m_to_hex(buf_, size_, hex);
    m_log_d(M_MAX7219_H, "reg_write-> reg=0x%02x, val=0x%02x, cmd=%s\n", (unsigned char)reg, (unsigned char)val, hex);
    #endif
    m_spi_data data = {
        .sendBuf = buf_,
        .recvBuf = buf_,
        .recvSize = size_
    };
    int r = m_spi_host_write_read(&data);
    m_delay(200);
    if (r != 0) {
        m_log_e(M_MAX7219_H, "max2719 reg write fail: reg=0x%02x, val=0x%02x, err=0x%02x\n", (unsigned char)reg, val, r);
        return r;
    }
    return 0;
}
